package com.uls.zsw.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.uls.common.core.domain.entity.SysRole;
import com.uls.common.core.domain.entity.SysUser;
import com.uls.common.core.domain.model.LoginUser;
import com.uls.common.utils.DateUtils;
import com.uls.common.utils.SecurityUtils;
import com.uls.common.utils.sign.Md5Utils;
import com.uls.czj.domain.CzjStudents;
import com.uls.czj.mapper.CzjStudentsMapper;
import com.uls.system.domain.SysCache;
import com.uls.system.domain.SysLogininfor;
import com.uls.system.domain.SysUserRole;
import com.uls.system.mapper.SysRoleMapper;
import com.uls.system.mapper.SysUserRoleMapper;
import com.uls.system.service.ISysUserService;
import com.uls.zsw.domain.ElectricityUsageInfo;
import com.uls.zsw.mapper.ElectricityManageMapper;
import com.uls.zsw.mapper.ElectricityUsageInfoMapper;
import com.uls.zsw.vo.BillingTaskCommentVo;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.uls.zsw.mapper.ElectricityBillingMapper;
import com.uls.zsw.domain.ElectricityBilling;
import com.uls.zsw.service.IElectricityBillingService;
import org.springframework.transaction.annotation.Transactional;
import sun.plugin2.util.SystemUtil;

import javax.servlet.http.Cookie;

/**
 * 电费结算Service业务层处理
 * 
 * @author zsw
 * @date 2024-12-28
 */
@Service
public class ElectricityBillingServiceImpl implements IElectricityBillingService 
{
    @Autowired
    private ElectricityBillingMapper electricityBillingMapper;
    @Autowired
    private ElectricityManageMapper electricityManageMapper;
    @Autowired
    private ElectricityUsageInfoMapper electricityUsageInfoMapper;
    @Autowired
    private CzjStudentsMapper czjStudentsMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询电费结算
     * 
     * @param billingId 电费结算主键
     * @return 电费结算
     */
    @Transactional
    @Override
    public ElectricityBilling selectElectricityBillingByBillingId(Long billingId)
    {
        ElectricityBilling electricityBilling=electricityBillingMapper.selectElectricityBillingByBillingId(billingId);
        ElectricityUsageInfo electricityUsageInfo=electricityUsageInfoMapper
                .selectElectricityUsageInfoByElectricityUsageId(electricityBilling.getElectricityUsageId());
        if(electricityUsageInfo!=null){
            String dn=electricityManageMapper.getDNByDI(electricityUsageInfo.getDormitoryId());
            electricityBilling.setSelecteddn(dn);
        }
        return electricityBilling;
    }

    /**
     * 查询电费结算列表
     * 
     * @param electricityBilling 电费结算
     * @return 电费结算
     */
    @Transactional
    @Override
    public List<ElectricityBilling> selectElectricityBillingList(ElectricityBilling electricityBilling)
    {
        List<SysRole> loginuserrole=sysRoleMapper.selectRolePermissionByUserId(SecurityUtils.getLoginUser().getUserId());
        for(SysRole loginuserrole1:loginuserrole){
            if(loginuserrole1.getRoleName().equals("学生")){
                Long studentnumber=Long.parseLong(SecurityUtils.getLoginUser().getUsername());
                CzjStudents czjStudents=czjStudentsMapper.selectCzjStudentByStudentNumber(studentnumber);
                electricityBilling.setSelecteddn(czjStudents.getCorrentDormitory());
            }
        }
        if(electricityBilling.getSelecteddn()!=null){
            Long di=electricityManageMapper.getDIByDN(electricityBilling.getSelecteddn());
            if(di!=null){
            ElectricityUsageInfo electricityUsageInfo=electricityUsageInfoMapper.selectElectricityUsageInfoByDormitoryId(di);
            electricityBilling.setElectricityUsageId(electricityUsageInfo.getElectricityUsageId());}
        }
        List<ElectricityBilling> electricityBillingList=electricityBillingMapper.selectElectricityBillingList(electricityBilling);
        if(electricityBillingList!=null) {
            for (ElectricityBilling electricityBilling1 : electricityBillingList) {
                ElectricityUsageInfo electricityUsageInfo1 = electricityUsageInfoMapper.selectElectricityUsageInfoByElectricityUsageId(electricityBilling1.getElectricityUsageId());
                String dn = electricityManageMapper.getDNByDI(electricityUsageInfo1.getDormitoryId());
                electricityBilling1.setSelecteddn(dn);
            }
        }
        return electricityBillingList;
    }

    /**
     * 新增电费结算
     * 
     * @param electricityBilling 电费结算
     * @return 结果
     */
    @Transactional
    @Override
    public int insertElectricityBilling(ElectricityBilling electricityBilling)
    {
        electricityBilling.setCreateTime(DateUtils.getNowDate());
        return electricityBillingMapper.insertElectricityBilling(electricityBilling);
    }

    /**
     * 修改电费结算
     * 
     * @param electricityBilling 电费结算
     * @return 结果
     */
    @Transactional
    @Override
    public int updateElectricityBilling(ElectricityBilling electricityBilling)
    {
        return electricityBillingMapper.updateElectricityBilling(electricityBilling);
    }

    /**
     * 批量删除电费结算
     * 
     * @param billingIds 需要删除的电费结算主键
     * @return 结果
     */
    @Override
    public int deleteElectricityBillingByBillingIds(Long[] billingIds)
    {
        return electricityBillingMapper.deleteElectricityBillingByBillingIds(billingIds);
    }

    /**
     * 删除电费结算信息
     * 
     * @param billingId 电费结算主键
     * @return 结果
     */
    @Override
    public int deleteElectricityBillingByBillingId(Long billingId)
    {
        return electricityBillingMapper.deleteElectricityBillingByBillingId(billingId);
    }

    /**
     * 提交审批流程
     *
     * @param billingId
     * @param userId
     * @return
     */
    @Transactional
    @Override
    public int submit(Long billingId, Long userId) {
        ElectricityBilling electricityBilling= electricityBillingMapper.selectElectricityBillingByBillingId(billingId);

        String processDefiKey ="electricitybilling";
        Map<String, Object> variables = new HashMap<String,Object>();
        variables.put("inputuser1",userId);
        variables.put("inputuser2","151");  //写死
        //没有启动这个流程
        if (electricityBilling.getPaymentStatus()==0) {
            ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefiKey, variables);
            electricityBilling.setFlowInstantId(Long.parseLong(pi.getProcessInstanceId()));  // 把流程实例id与业务系统绑定
            electricityBilling.setPaymentStatus(2);//状态(0-未提交，1-打回，2-审核中，3-已完成）
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .taskAssignee(""+userId)
                    .processInstanceId(pi.getProcessInstanceId())
                    .list();
            Task task=list.get(0);
            taskService.complete(task.getId());

            return  electricityBillingMapper.updateElectricityBilling(electricityBilling);
        }
        //流程启动了，打回重新审批，就不用再启动流程
        else{
            Long flowInstantId=electricityBilling.getFlowInstantId();
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .processInstanceId("" + flowInstantId)
                    .list();
            Task task=list.get(0);
            taskService.complete(task.getId());
            electricityBilling.setPaymentStatus(2);//状态(0-未提交，1-打回，2-审核中，3-已完成）
            return electricityBillingMapper.updateElectricityBilling(electricityBilling);
        }
    }

    /**
     * 待审批项
     *
     * @param userId
     * @param processDefinitionKey
     * @return
     */
    @Transactional
    @Override
    public List<ElectricityBilling> noConfirmTask(Long userId, String processDefinitionKey) {
        List<ElectricityBilling> electricityBillingList=new ArrayList<>();
        TaskQuery taskQuery=taskService.createTaskQuery();
        List<Task> list=taskQuery
                .taskAssignee(""+userId)
                .processDefinitionKey(processDefinitionKey)
                .list();
        if(list!=null&&list.size()>0){
            for (Task task:list){
                if(!task.getName().equals("支付提交")){
                    Long flowInstanceId=Long.parseLong(task.getProcessInstanceId());
                    ElectricityBilling electricityBilling=electricityBillingMapper.selectElectricityBillingFlowId(flowInstanceId);
                    electricityBillingList.add(electricityBilling);
                }
            }
        }
        return electricityBillingList;
    }

    /**
     * 进行审批
     *
     * @param electricityBilling
     * @param userId
     */

    @Transactional
    @Override
    public void completeTask(ElectricityBilling electricityBilling, Long userId) {
        TaskQuery taskQuery=taskService.createTaskQuery();
        List<Task> list=taskQuery
                .processInstanceId(""+electricityBilling.getFlowInstantId())
                .list();
        Map<String,Object> params=new HashMap<>();
        if(list!=null&&list.size()>0){
            for(Task task:list){
                if(task.getName().equals("宿管审批")){
                    if(electricityBilling.getConfirmresult()==1){
                        params.put("inputuser3",157);
                        electricityBilling.setPaymentStatus(2);
                    }else{
                        electricityBilling.setPaymentStatus(3);
                    }
                    params.put("pass1",electricityBilling.getConfirmresult());
                }else if(task.getName().equals("财务审批")){
                    if(electricityBilling.getConfirmresult()==1){
                        params.put("inputuser4",158);
                        electricityBilling.setPaymentStatus(2);
                    }else{
                        electricityBilling.setPaymentStatus(3);
                    }
                    params.put("pass2",electricityBilling.getConfirmresult());
                }else {
                    if(electricityBilling.getConfirmresult()==1){
                        electricityBilling.setPaymentStatus(1);
                    }else{
                        electricityBilling.setPaymentStatus(3);
                    }
                    params.put("pass3",electricityBilling.getConfirmresult());
                }

                electricityBillingMapper.updateElectricityBilling(electricityBilling);

                Authentication.setAuthenticatedUserId(userId.toString());

                taskService.addComment(task.getId(),task.getProcessInstanceId(),electricityBilling.getConfirmcomment());

                taskService.complete(task.getId(),params);
            }
        }
    }

    /**
     * 获取审批的记录
     * @param flowInstantId
     * @return
     */
    @Transactional
    @Override
    public List<BillingTaskCommentVo> getTaskCommentList(Long flowInstantId) {
        List<BillingTaskCommentVo> billingTaskCommentVoList=new ArrayList<>();
        List<Comment> list=new ArrayList<>();
        list=taskService.getProcessInstanceComments(""+flowInstantId);
        for(Comment comment:list){
            BillingTaskCommentVo billingTaskCommentVo=new BillingTaskCommentVo();
            billingTaskCommentVo.setMessage(comment.getFullMessage());
            SysUser user=userService.selectUserById(Long.parseLong(comment.getUserId()));
            billingTaskCommentVo.setUserName(user.getUserName());

            List<HistoricTaskInstance> htilist=historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(""+flowInstantId)
                    .taskId(comment.getTaskId())
                    .list();
            if(htilist!=null&&htilist.size()>0){
                HistoricTaskInstance historicTaskInstance=htilist.get(0);
                billingTaskCommentVo.setTaskKeyId(historicTaskInstance.getTaskDefinitionKey());
                billingTaskCommentVo.setTaskName(historicTaskInstance.getName());
            }
            billingTaskCommentVoList.add(billingTaskCommentVo);
        }

        //排序
        List<BillingTaskCommentVo> billingTaskCommentVoListSort=new ArrayList<>();

        for(int i= billingTaskCommentVoList.size()-1;i>=0;i--)
        {
            BillingTaskCommentVo temp=billingTaskCommentVoList.get(i);
            billingTaskCommentVoListSort.add(temp);
        }

        return billingTaskCommentVoListSort;
    }

}
